package com.fjwt.gz.proxy.ctrl;

import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.ctrls.AbstractCtrl;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.SmsConfig;
import com.fjwt.gz.core.model.security.GzUserDetails;
import com.fjwt.gz.core.utils.AliyunSMSKit;
import com.fjwt.gz.core.utils.JsonKit;
import com.fjwt.gz.proxy.config.SystemYmlConfig;
import com.fjwt.gz.service.impl.AgentInfoService;
import com.fjwt.gz.service.impl.SysConfigService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;

/**
* 定义通用CommonCtrl
*
* @author wg
* @site https://pt.jdyd.xyz/
* @date 2021/6/8 17:09
*/
public abstract class CommonCtrl extends AbstractCtrl {

    @Autowired protected SystemYmlConfig mainConfig;

    @Autowired protected SysConfigService sysConfigService;

    @Autowired protected AgentInfoService agentInfoService;

    /** 获取当前用户ID */
    protected GzUserDetails getCurrentUser(){

        return (GzUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /** 获取当前商户ID **/
    protected String getCurrentAgentNo() {
        return getCurrentUser().getSysUser().getBelongInfoId();
    }

    /**
     * 获取当前用户登录IP
     * @return
     */
    protected String getIp() {
        return getClientIp();
    }

    /** 获取短信验证码 **/
    protected String genSmsCode(){
        String code = "";
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            for (int i = 0; i < 6; i++) {
                int number = random.nextInt(9);
                code += number;
            }
        } catch (NoSuchAlgorithmException nsae) {
        }
        logger.info("短信验证码：{}",code);
       return code;
    }

    /** 发送短信验证码 **/
    protected void sendSms(String phone, SmsConfig smsConfig, String templateId) {
        // 生成短信验证码
        String verifyCode = genSmsCode();
        // 将短信验证码存在redis中
        JSONObject codeObj = new JSONObject();
        codeObj.put("mobile", phone);
        codeObj.put("code", verifyCode);
        codeObj.put("time", System.currentTimeMillis());

        logger.info("手机号:{},短信验证码:{}", phone, verifyCode);

        // 短信验证码缓存时间: 1分钟
        RedisUtil.setString(CS.getCacheKeySmsCode(CS.SYS_ROLE_TYPE.PROXY, phone), codeObj.toJSONString(), 60);

        //发送 短信
        AliyunSMSKit.send(smsConfig, templateId, phone, JsonKit.newJson("code", verifyCode));
    }

    /**
     * @author: xiaoyu
     * @date: 2022/2/14 15:28
     * @describe: 获取短信配置参数
     */
    public SmsConfig getSmsConfig() {
        try {
            // 短信参数配置
            JSONObject smsConfigJson = sysConfigService.selectByGroupKey("smsConfig");
            SmsConfig smsConfig = SmsConfig.parse(smsConfigJson.getString("smsConfigValue"));
            return smsConfig;
        }catch (BizException e) {
            throw new BizException("获取短信配置参数异常。"+e.getMessage());
        }
    }

    /**
     * @author: xiaoyu
     * @date: 2022/2/14 16:30
     * @describe: 发送短信验证
     */
    public void sendSmsCode(String phone, String smsType) {
        try {
            // 短信参数配置
            SmsConfig smsConfig = getSmsConfig();
            String smsTemplateId = "";
            if (SmsConfig.TYPE_AUTH.equals(smsType)) {
                smsTemplateId = smsConfig.getLoginMchTemplateId();
            }else if (SmsConfig.TYPE_REGISTER.equals(smsType)) {
                smsTemplateId = smsConfig.getRegisterMchTemplateId();
            }else if (SmsConfig.TYPE_RETRIEVE.equals(smsType)) {
                smsTemplateId = smsConfig.getForgetPwdTemplateId();
            }
            // 发送短信
            sendSms(phone, smsConfig, smsTemplateId);
        }catch (BizException e) {
            throw new BizException("发送短信异常。"+e.getMessage());
        }
    }

    /**
     * 判断是否有对应机构权限
     * @param tokenAgentNo
     * @param queryAgentNo
     * @return
     */
    public String checkAgentAuth(String tokenAgentNo, String queryAgentNo) {
        if (ObjectUtils.isEmpty(queryAgentNo)) {
            return tokenAgentNo;
        }else {
            List<String> allSubAgentNos = agentInfoService.queryAllSubAgentNo(tokenAgentNo);
            if (!allSubAgentNos.contains(queryAgentNo)) {
                throw new BizException("不允许操作非下级机构");
            }
        }
        return queryAgentNo;
    }

}
